package com.qsl.ssyx.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.math.LongMath;
import com.qsl.ssyx.activity.mapper.ActivityRuleMapper;
import com.qsl.ssyx.activity.service.ActivityRuleService;
import com.qsl.ssyx.activity.service.ActivitySkuService;
import com.qsl.ssyx.activity.service.CouponInfoService;
import com.qsl.ssyx.client.product.ProductFeignClient;
import com.qsl.ssyx.enums.ActivityType;
import com.qsl.ssyx.model.activity.ActivityInfo;
import com.qsl.ssyx.activity.mapper.ActivityInfoMapper;
import com.qsl.ssyx.activity.service.ActivityInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qsl.ssyx.model.activity.ActivityRule;
import com.qsl.ssyx.model.activity.ActivitySku;
import com.qsl.ssyx.model.activity.CouponInfo;
import com.qsl.ssyx.model.order.CartInfo;
import com.qsl.ssyx.model.product.SkuInfo;
import com.qsl.ssyx.vo.activity.ActivityRuleVo;
import com.qsl.ssyx.vo.order.CartInfoVo;
import com.qsl.ssyx.vo.order.OrderConfirmVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sun.java2d.pipe.hw.AccelTypedVolatileImage;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author 青衫泪
 * @since 2023-08-28
 */
@Service
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo> implements ActivityInfoService {

    @Autowired
    private ActivityRuleService activityRuleService;
    @Autowired
    private ActivitySkuService activitySkuService;
    @Autowired
    private ProductFeignClient productFeignClient; // 远程调用
    @Autowired
    private CouponInfoService couponInfoService;

    //    条件分页查询
    @Override
    public IPage<ActivityInfo> selectPage(Page<ActivityInfo> pageParam) {
        LambdaQueryWrapper<ActivityInfo> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(ActivityInfo::getId); //倒序排序
        Page<ActivityInfo> activityInfoPage = baseMapper.selectPage(pageParam, lqw);
        // 获取数据
        List<ActivityInfo> activityInfoList = activityInfoPage.getRecords();
        // 遍历activityInfoList集合，并设置活动类型（满减、折扣）
        activityInfoList.stream().forEach(item -> item.setActivityTypeString(item.getActivityType().getComment()));
        return activityInfoPage;
    }

    // 根据营销活动Id查询 营销活动规则和活动范围
    @Override
    public Map<String, Object> getActivityRuleById(Integer activityInfoId) {
        // 封装最终返回数据集合
        Map<String, Object> result = new HashMap<>();
        // 1.根据营销活动Id查询 营销活动规则
        LambdaQueryWrapper<ActivityRule> lqwActivityRule = new LambdaQueryWrapper<>();
        lqwActivityRule.eq(ActivityRule::getActivityId, activityInfoId);
        lqwActivityRule.orderByDesc(ActivityRule::getId); //倒序
        List<ActivityRule> activityRuleList = activityRuleService.list(lqwActivityRule);
        // 封装返回数据
        result.put("activityRuleList", activityRuleList);

        //2 根据营销活动Id查询 活动范围
        LambdaQueryWrapper<ActivitySku> lqwActivitySku = new LambdaQueryWrapper<>();
        lqwActivitySku.eq(ActivitySku::getActivityId, activityInfoId);
        lqwActivitySku.orderByDesc(ActivitySku::getId); //倒序
        List<ActivitySku> activitySkuList = activitySkuService.list(lqwActivitySku);

        // 3. 根据活动范围中的skuId,查询sku_info商品表
        //// 获取SkuId集合
        List<Long> SkuIdList = activitySkuList.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(SkuIdList)) { // 集合不为空
            for (Long skuId : SkuIdList) {
                List<SkuInfo> skuInfoList = productFeignClient.getSkuInfoList(skuId);
                result.put("skuInfoList", skuInfoList);
            }
        }
        return result;
    }

    // 根据ActivityInfoId删除，`activity_info``activity_rule``activity_sku`
    @Override
    public boolean removeByActivityInfoId(Integer activityInfoId) {
        // 删除 activity_info
        int activityInfoCount = baseMapper.deleteById(activityInfoId);

        // 删除 activity_rule
        LambdaQueryWrapper<ActivityRule> lqwActivityRule = new LambdaQueryWrapper<>();
        lqwActivityRule.eq(ActivityRule::getActivityId, activityInfoId);
        activityRuleService.remove(lqwActivityRule);

        // 删除 activity_sku
        LambdaQueryWrapper<ActivitySku> lqwActivitySku = new LambdaQueryWrapper<>();
        lqwActivitySku.eq(ActivitySku::getActivityId, activityInfoId);
        activitySkuService.remove(lqwActivitySku);
        return true;
    }

    //    新增规则： `activity_info``activity_rule``activity_sku`
    @Override
    public boolean saveActivityRule(ActivityRuleVo activityRuleVo) {
        // 先删除旧数据，在新增
        //ActivityRule数据删除
        Long activityId = activityRuleVo.getActivityId();
        activityRuleService.remove(
                new LambdaQueryWrapper<ActivityRule>().eq(ActivityRule::getActivityId, activityId)
        );
        //ActivitySku数据删除
        activitySkuService.remove(
                new LambdaQueryWrapper<ActivitySku>().eq(ActivitySku::getActivityId, activityId)
        );

        // 新增activity_rule 活动规则集合
        boolean flagActivityRule = activityRuleService.saveBatch(activityRuleVo.getActivityRuleList());

        // 新增activity_sku 活动参与商品集合
        for (ActivitySku activitySku : activityRuleVo.getActivitySkuList()) {
            activitySku.setActivityId(activityRuleVo.getActivityId());
        }
        boolean flagActivitySku = activitySkuService.saveBatch(activityRuleVo.getActivitySkuList());

        return true;
    }

    //    根据skuId列表获取促销信息
    @Override
    public Map<Long, List<String>> getActivityInfoBySkuId(List<Long> skuIdList) {
        Map<Long, List<String>> result = new HashMap<>();
        // 遍历skuId集合，获取skuid
        skuIdList.forEach(skuId -> {
            // 根据商品Id获取商品对应活动规则
            List<ActivityRule> activityRuleList = baseMapper.findActivityRule(skuId);

            // 封装规则名称返回
            if (!CollectionUtils.isEmpty(activityRuleList)) {
                List<String> ruleList = new ArrayList<>();
                for (ActivityRule activityRule : activityRuleList) {
                    ruleList.add(this.getRuleDesc(activityRule));
                }
                result.put(skuId, ruleList);
            }
        });
        return result;
    }

    //    根据商品id和用户id获取优惠卷信息
    @Override
    public Map<String, Object> getActivityInfoBySkuIdAndUserId(Long skuId, Long userId) {
        //1 根据skuId获取sku营销活动，一个活动有多个规则
        List<ActivityRule> activityRuleList = this.getActivityRuleBySkuId(skuId);

        //2 根据skuId+userId查询优惠卷信息
        List<CouponInfo> couponInfoList = couponInfoService.getCouponInfoBySkuIdAndUserId(skuId, userId);

        //3 封装数据返回
        Map<String, Object> map = new HashMap<>();
        map.put("couponInfoList", couponInfoList);
        map.put("activityRuleList", activityRuleList);
        return map;
    }

    //    根据商品id查询优惠卷信息
    @Override
    public List<ActivityRule> getActivityRuleBySkuId(Long skuId) {
        // 根据商品id查询`activity_info``activity_rule``activity_sku`
        List<ActivityRule> activityRuleList = baseMapper.findActivityRule(skuId);
        for (ActivityRule activityRule : activityRuleList) {
            String ruleDesc = this.getRuleDesc(activityRule);
            activityRule.setRuleDesc(ruleDesc);
        }
        return activityRuleList;
    }

    //    获取购物车里面满足条件优惠卷和活动的信息
    @Override
    public OrderConfirmVo findCartActivityAndCoupon(List<CartInfo> cartInfoList, Long userId) {
        // 1. 获取购物车，          //一个规则对应多个商品
        List<CartInfoVo> cartInfoVoList = this.finCartActivityList(cartInfoList);

        // 2.计算使用优惠卷之后的金额
        BigDecimal activityReduceAmount = cartInfoVoList.stream().filter(item -> item.getActivityRule() != null)
                .map(item -> item.getActivityRule().getReduceAmount())
                .reduce(BigDecimal.ZERO, BigDecimal::add);// 默认金额为零，

        // 3. 获取购物车删除可以使用优惠卷列表
        List<CouponInfo> couponInfoList = couponInfoService.findCartCouponInfo(cartInfoList, userId);

        // 4.计算购物车商品使用优惠卷之后的金额，一次只能使用一张优惠卷
        BigDecimal couponReduceAmount = new BigDecimal(0);
        if (!CollectionUtils.isEmpty(couponInfoList)) {
            couponReduceAmount = couponInfoList.stream().filter(item -> item.getIsOptimal().intValue() == 1)
                    .map(item -> item.getAmount())
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
        }

        // 5 计算没有参与活动，没有使用优惠卷原始金额
        BigDecimal originalTotalAmount = cartInfoList.stream().filter(item -> item.getIsChecked() == 1)
//                .map(item -> item.getCartPrice() == null ? 0 : item.getCartPrice().multiply(new BigDecimal(item.getSkuNum())))
                // TODO 金额为空
                .map(item -> new  BigDecimal(item.getSkuNum()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 6 最终金额
        BigDecimal totalAmount = originalTotalAmount.subtract(activityReduceAmount).subtract(couponReduceAmount);

        // 封装数据返回
        OrderConfirmVo orderTradeVo = new OrderConfirmVo();
        orderTradeVo.setCarInfoVoList(cartInfoVoList); // 购物项列表
        orderTradeVo.setActivityReduceAmount(activityReduceAmount); // 促销优惠金额
        orderTradeVo.setCouponInfoList(couponInfoList); // 订单优惠券列表
        orderTradeVo.setCouponReduceAmount(couponReduceAmount); // 优惠券优惠金额
        orderTradeVo.setOriginalTotalAmount(originalTotalAmount); // 购物车原始总金额
        orderTradeVo.setTotalAmount(totalAmount); // 最终总金额
        return orderTradeVo;
    }

    //    促销活动相关信息
    @Override
    public List<CartInfoVo> findCartActivityList(List<CartInfo> cartInfoList) {
        // 封装最终返回数据
        List<CartInfoVo> cartInfoVoList = new ArrayList<>();
        // 获取所有skuId
        List<Long> skuIdList = cartInfoList.stream().map(CartInfo::getSkuId).collect(Collectors.toList());
        // 根据所有skuId列表获取参数活动
        List<ActivitySku> activitySkuList = baseMapper.selectCartActivity(skuIdList);
        // 根据活动对skuId进行分组
        // map ==> key是活动id; value为sku列表数据（set集合）
        Map<Long, Set<Long>> activityIdToSkuIdListMap = activitySkuList.stream()
                .collect(
                        Collectors.groupingBy(
                                ActivitySku::getActivityId,
                                Collectors.mapping(ActivitySku::getSkuId, Collectors.toSet())
                        )
                );

        //  获取活动规则数据
        Map<Long, List<ActivityRule>> activityIdToActivityRuleListMap = new HashMap<>();
        // 获取所有活动id,不重复
        Set<Long> activityIdSet = activitySkuList.stream().map(item -> item.getActivityId()).collect(Collectors.toSet());
        if (!CollectionUtils.isEmpty(activityIdSet)) {
            // 根据优惠卷ID子查询activity_rule表,并根据优惠卷金额和数量分组。
            List<ActivityRule> activityRuleList = activityRuleService.getActivityRuleBy(activityIdSet);

            // 根据活动ID分组
            activityIdToActivityRuleListMap = activityRuleList.stream().collect(Collectors.groupingBy(item -> item.getActivityId()));
        }

        // 有活动的购物车商品
        HashSet<Long> activitySkuIdSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(activityIdToActivityRuleListMap)) {
            // 遍历
            Iterator<Map.Entry<Long, Set<Long>>> iterator = activityIdToSkuIdListMap.entrySet().iterator();
            while (iterator.hasNext()) { // 如果迭代具有更多元素，则返回true
                Map.Entry<Long, Set<Long>> entry = iterator.next(); // 返回迭代中的下一个元素
                // 活动id
                Long activityId = entry.getKey();
                // 商品id
                Set<Long> currentActivitySkuIdSet = entry.getValue();
                // 获取当前活动对应的购物车商品列表
                List<CartInfo> currentActivityCartInfoList = cartInfoList.stream()
                        .filter(item -> currentActivitySkuIdSet.contains(item.getSkuId())).collect(Collectors.toList());
                // 计算购物车总金额和总数量
                BigDecimal activityTotalAmount = this.computeTotalAmount(currentActivityCartInfoList);
                int activityTotalNum = this.computeCartNum(currentActivityCartInfoList);

                // 计算活动对应规则
                List<ActivityRule> currentActivityRuleList = activityIdToActivityRuleListMap.get(activityId);
                ActivityType activityType = currentActivityRuleList.get(0).getActivityType();
                //  活动类型（满减、折扣）
                ActivityRule activityRule = null;
                if (activityType == ActivityType.FULL_REDUCTION) { // 活动类型-满减
                    activityRule = this.computeFullReduction(activityTotalAmount, currentActivityRuleList);
                } else {//活动类型-满量
                    activityRule = this.computeFullDiscount(activityTotalNum, activityTotalAmount, currentActivityRuleList);
                }

                // CartInfoVo封装
                CartInfoVo cartInfoVo = new CartInfoVo();
                cartInfoVo.setActivityRule(activityRule);  // 活动规则
                cartInfoVo.setCartInfoList(currentActivityCartInfoList);  // 购物项凑单，同一活动对应的最优活动规则
                cartInfoVoList.add(cartInfoVo);

                //记录哪些购物项参与活动
                activitySkuIdSet.addAll(currentActivitySkuIdSet);
            }
        }

        // 没有活动购物项skuId
        //获取所有没有参加活动的skuId
        skuIdList.removeAll(activitySkuIdSet);
        if (!CollectionUtils.isEmpty(skuIdList)) {
            // 获取商品id，和购物车商品
            Map<Long, CartInfo> skuIdCartInfoMap =
                    cartInfoList.stream().collect(
                            Collectors.toMap(CartInfo::getSkuId, CartInfo -> CartInfo));

            for (Long skuId : skuIdList) {
                CartInfoVo cartInfoVo = new CartInfoVo();
                cartInfoVo.setActivityRule(null); // 没有活动

                ArrayList<CartInfo> cartInfos = new ArrayList<>();
                cartInfos.add(skuIdCartInfoMap.get(skuId));
                cartInfoVo.setCartInfoList(cartInfos);

                cartInfoVoList.add(cartInfoVo);
            }
        }

        return cartInfoVoList;
    }


    // 计算购物车总金额和总数量
    private BigDecimal computeTotalAmount(List<CartInfo> cartInfoList) {
        BigDecimal total = new BigDecimal("0");
        for (CartInfo cartInfo : cartInfoList) {
            // 购物车商品是否选中
            if (cartInfo.getIsChecked().intValue() == 1) {
                // 放入购物车时价格  乘于  商品数量
                BigDecimal itemTotal = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
                total = total.add(itemTotal);
            }
        }
        return total;
    }


    //获取购物车商品对应活动规则数据
    private List<CartInfoVo> finCartActivityList(List<CartInfo> cartInfoList) {
        // 封装最终返回数据
        List<CartInfoVo> cartInfoVoList = new ArrayList<>();
        // 获取所有SkuId
        List<Long> skuIdList = cartInfoList.stream().map(CartInfo::getSkuId).collect(Collectors.toList());
        // 根据所有skuId列表获取商品参与的活动信息
        List<ActivitySku> activitySkuList = baseMapper.selectCartActivity(skuIdList);
        // 根据活动进行分组,   key:活动ID，val:sku列表数据，set集合（不重复）
        Map<Long, Set<Long>> activityIdToSkuListMap = activitySkuList.stream().collect(
                Collectors.groupingBy(ActivitySku::getActivityId,
                        Collectors.mapping(ActivitySku::getSkuId, Collectors.toSet())));

        // 获取活动里面规则数据  ===》 key:活动ID，val:sku列表数据，set集合（不重复）
        Map<Long, List<ActivityRule>> activityIdToActivityRuleListMap = new HashMap<>();

        // 所有活动id
        Set<Long> activityIdSet = activitySkuList.stream().map(ActivitySku::getActivityId).collect(Collectors.toSet());

        // 活动规则表不为空， 根据满减金额倒序排序，若相同，则根据满减件数排序
        if (!CollectionUtils.isEmpty(activityIdSet)) {
            // ActivityRule表
            LambdaQueryWrapper<ActivityRule> lqw = new LambdaQueryWrapper<>();
            // 根据满减金额倒序排序，若相同，则根据满减件数排序
            lqw.orderByDesc(ActivityRule::getConditionAmount, ActivityRule::getConditionNum);
            // in为条件筛选,筛选出activityId在activityIdSet集合中的记录。
            lqw.in(ActivityRule::getActivityId, activityIdSet);
            List<ActivityRule> activityRuleList = activityRuleService.list(lqw);

            //封装到activityIdToActivityRuleListMap里面
            //根据活动id进行分组
            activityIdToActivityRuleListMap = activityRuleList.stream().collect(Collectors.groupingBy(activityRule -> activityRule.getActivityId()));

        }

        // 有活动的购物车商品 skuId
        Set<Long> activitySkuIdSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(activityIdToSkuListMap)) {
            // 迭代器遍历activityIdToSkuListMap集合
            Iterator<Map.Entry<Long, Set<Long>>> iterator = activityIdToSkuListMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, Set<Long>> entry = iterator.next();
                // 活动id
                Long activityId = entry.getKey();
                // 每个活动对应skuId列表
                Set<Long> currentActivitySkuIdSet = entry.getValue();
                // 获取当前活动对应的购物车商品列表
                List<CartInfo> currentActivityCartInfoList = cartInfoList.stream()
                        .filter(item -> currentActivitySkuIdSet.contains(item.getSkuId())).collect(Collectors.toList());

                // 计算购物车商品总金额
                BigDecimal activityTotalAmount = this.computeTotalAmout(currentActivityCartInfoList);
                // 总数量
                int activityTotalNum = this.computeCartNum(currentActivityCartInfoList);

                // 计算活动对应规则
                // 根据activityId获取活动对应规则
                List<ActivityRule> currentActivityRuleList = activityIdToActivityRuleListMap.get(activityId);
                ActivityType activityType = currentActivityRuleList.get(0).getActivityType();
                // 判断活动类型： ①满减 ②打折
                ActivityRule activityRule = null;
                if (activityType == ActivityType.FULL_REDUCTION) { // 满减
                    activityRule = this.computeFullReduction(activityTotalAmount, currentActivityRuleList);
                } else { // 满量打折
                    activityRule = this.computeFullDiscount(activityTotalNum, activityTotalAmount, currentActivityRuleList);
                }

                //CartInfoVo封装
                CartInfoVo cartInfoVo = new CartInfoVo();
                cartInfoVo.setActivityRule(activityRule);
                cartInfoVo.setCartInfoList(currentActivityCartInfoList);
                cartInfoVoList.add(cartInfoVo);

                //记录哪些购物项参与活动
                activitySkuIdSet.addAll(currentActivitySkuIdSet);
            }
        }

        //没有活动购物项skuId-获取哪些skuId没有参加活动
        skuIdList.removeAll(activitySkuIdSet);
        if (!CollectionUtils.isEmpty(skuIdList)) {
            //skuId对应购物除商品
            Map<Long, CartInfo> skuIdCartInfoMap = cartInfoList.stream().collect(Collectors.toMap(CartInfo::getSkuId, CartInfo -> CartInfo));

            for (Long skuId : skuIdList) {
                CartInfoVo cartInfoVo = new CartInfoVo();
                cartInfoVo.setActivityRule(null); // 没有活动

                List<CartInfo> cartInfos = new ArrayList<>();
                cartInfos.add(skuIdCartInfoMap.get(skuId));
                cartInfoVo.setCartInfoList(cartInfos);

                cartInfoVoList.add(cartInfoVo);
            }
        }
        return cartInfoVoList;
    }

    // 满量打折
    private ActivityRule computeFullDiscount(Integer totalNum, BigDecimal totalAmount, List<ActivityRule> activityRuleList) {
        ActivityRule optimalActivityRule = null;
        //  该活动规则skuActivityRuleList数据，已经按照优惠金额从大到小排序
        for (ActivityRule activityRule : activityRuleList) {
            // 如果订单商品购买个数大于满减件数，则优化打折
            if (totalNum.intValue() >= activityRule.getConditionNum()) {
                BigDecimal skuDiscountTotalAmount = totalAmount.multiply(activityRule.getBenefitDiscount()).divide(new BigDecimal("10"));
                BigDecimal reduceAmount = totalAmount.subtract(skuDiscountTotalAmount);
                activityRule.setReduceAmount(reduceAmount);
                optimalActivityRule = activityRule;
                break;
            }
        }

        if (optimalActivityRule == null) {
            //如果没有满足条件的取最小满足条件的一项
            optimalActivityRule = activityRuleList.get(activityRuleList.size() - 1);
            optimalActivityRule.setReduceAmount(new BigDecimal("0"));
            optimalActivityRule.setSelectType(1);

            StringBuffer ruleDesc = new StringBuffer()
                    .append("满")
                    .append(optimalActivityRule.getConditionNum())
                    .append("元打")
                    .append(optimalActivityRule.getBenefitDiscount())
                    .append("折，还差")
                    .append(totalNum - optimalActivityRule.getConditionNum())
                    .append("件");
            optimalActivityRule.setRuleDesc(ruleDesc.toString());
        } else {
            StringBuffer ruleDesc = new StringBuffer()
                    .append("满")
                    .append(optimalActivityRule.getConditionNum())
                    .append("元打")
                    .append(optimalActivityRule.getBenefitDiscount())
                    .append("折，已减")
                    .append(optimalActivityRule.getReduceAmount())
                    .append("元");
            optimalActivityRule.setRuleDesc(ruleDesc.toString());
            optimalActivityRule.setSelectType(2);
        }
        return optimalActivityRule;
    }


    /**
     * 计算满减最优规则
     *
     * @param totalNum         计算购物车商品总金额
     * @param activityRuleList 该活动规则skuActivityRuleList数据，已经按照优惠金额从大到小排序
     * @return
     */
    private ActivityRule computeFullReduction(BigDecimal totalNum, List<ActivityRule> activityRuleList) {
        ActivityRule optimalActivityRule = null;
        //  该活动规则skuActivityRuleList数据，已经按照优惠金额从大到小排序
        for (ActivityRule activityRule : activityRuleList) {
            // 如果订单金额大于满减金额，
            if (totalNum.compareTo(activityRule.getConditionAmount()) > -1) {
                // 优惠后商品金额减少
                activityRule.setReduceAmount(activityRule.getBenefitAmount());
                optimalActivityRule = activityRule;
                break;
            }
        }
        if (optimalActivityRule == null) {
            // 如果没有满足条件的取最小满足条件的一项
            optimalActivityRule = activityRuleList.get(activityRuleList.size() - 1);
            optimalActivityRule.setReduceAmount(new BigDecimal("0"));
            optimalActivityRule.setSelectType(1);

            StringBuffer ruleDesc = new StringBuffer()
                    .append("满")
                    .append(optimalActivityRule.getConditionNum())
                    .append("元打")
                    .append(optimalActivityRule.getBenefitDiscount())
                    .append("折，还差")
                    .append(totalNum.subtract(optimalActivityRule.getConditionAmount()))
                    .append("件");
            optimalActivityRule.setRuleDesc(ruleDesc.toString());
        } else {
            StringBuffer ruleDesc = new StringBuffer()
                    .append("满")
                    .append(optimalActivityRule.getConditionAmount())
                    .append("元减")
                    .append(optimalActivityRule.getBenefitAmount())
                    .append("元，已减")
                    .append(optimalActivityRule.getReduceAmount())
                    .append("元");
            optimalActivityRule.setRuleDesc(ruleDesc.toString());
            optimalActivityRule.setSelectType(2);
        }
        return optimalActivityRule;
    }

    // 获取购物车商品总数量
    private int computeCartNum(List<CartInfo> cartInfoList) {
        int total = 0;
        for (CartInfo cartInfo : cartInfoList) {
            // 是否选中
            if (cartInfo.getIsChecked().intValue() == 1) {
                // 商品数量
                total += cartInfo.getSkuNum();
            }
        }
        return total;
    }

    // 获取购物车商品总金额
    private BigDecimal computeTotalAmout(List<CartInfo> cartInfoList) {
        BigDecimal total = new BigDecimal(0);
        for (CartInfo cartInfo : cartInfoList) {
            // 是否选中
            if (cartInfo.getIsChecked().intValue() == 1) {
                //  购物车价格 乘以 商品数量
                if (cartInfo.getCartPrice() != null) {
                    BigDecimal itemTotal = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
                    total = total.add(itemTotal);
                }
            }
        }
        return total;
    }


    //构造规则名称的方法
    private String getRuleDesc(ActivityRule activityRule) {
        ActivityType activityType = activityRule.getActivityType();
        StringBuffer stringBuffer = new StringBuffer();
        if (activityType == ActivityType.FULL_DISCOUNT) { // 满量打折
            stringBuffer.append("满")
                    .append(activityRule.getConditionAmount())
                    .append("元减")
                    .append(activityRule.getBenefitAmount())
                    .append("元");
        } else { // 满减
            stringBuffer.append("满")
                    .append(activityRule.getConditionAmount())
                    .append("元打")
                    .append(activityRule.getBenefitAmount())
                    .append("折");
        }
        return stringBuffer.toString();
    }


}
